package service

import (
    "errors"
    "generator-tool/models"
    "generator-tool/repository"
)

type ShGoodService struct {
    Repo *repository.ShGoodRepository
}

func NewShGoodService(repo *repository.ShGoodRepository) *ShGoodService {
    return &ShGoodService{Repo: repo}
}

func (s *ShGoodService) CreateShGood(ShGood *models.ShGood) error {
    return s.Repo.CreateShGood(ShGood)
}

func (s *ShGoodService) GetAllShGoods() ([]models.ShGood, error) {
    return s.Repo.GetAllShGoods()
}

func (s *ShGoodService) GetShGoodByID(id uint) (*models.ShGood, error) {
    if id == 0 {
        return nil, errors.New("invalid id")
    }
    return s.Repo.GetShGoodByID(id)
}

func (s *ShGoodService) UpdateShGood(id uint, ShGood *models.ShGood) error {
    existing, err := s.Repo.GetShGoodByID(id)
    if err != nil {
        return errors.New("record not found")
    }

    // Copy fields (skip primary key)
    existing.CategoryId = ShGood.CategoryId
    existing.Sn = ShGood.Sn
    existing.Name = ShGood.Name
    existing.Keyword = ShGood.Keyword
    existing.Picture = ShGood.Picture
    existing.Tips = ShGood.Tips
    existing.Description = ShGood.Description
    existing.Content = ShGood.Content
    existing.Price = ShGood.Price
    existing.Stock = ShGood.Stock
    existing.Score = ShGood.Score
    existing.IsOnSale = ShGood.IsOnSale
    existing.IsDel = ShGood.IsDel
    existing.IsFreeShipping = ShGood.IsFreeShipping
    existing.SellCount = ShGood.SellCount
    existing.CommentCount = ShGood.CommentCount
    existing.OnSaleTime = ShGood.OnSaleTime
    existing.CreateTime = ShGood.CreateTime
    existing.UpdateTime = ShGood.UpdateTime

    return s.Repo.UpdateShGood(existing)
}

func (s *ShGoodService) DeleteShGood(id uint) error {
    _, err := s.Repo.GetShGoodByID(id)
    if err != nil {
        return errors.New("record not found")
    }
    return s.Repo.DeleteShGood(id)
}